<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-row>
          <el-col span="24">
            <el-form-item label="报表名称：" prop="name" class="lWidth">
              <el-input
                v-model="formData.name"
                placeholder="请输入"
                clearable=""
              ></el-input>
            </el-form-item>
            <el-form-item label="报表说明：" prop="description">
              <el-input
                v-model="formData.description"
                clearable=""
                placeholder="请输入"
                :rows="5"
                type="textarea"
              ></el-input>
            </el-form-item>
            <el-form-item label="列字段：" prop="treeData">
              <el-tree
                class="elTree"
                ref="headerList"
                :data="treeData"
                :props="defaultProps"
                node-key="id"
                :check-strictly="checkStrictly"
                :default-checked-keys="checkedKeys"
                @check-change="handleCheckChange"
                accordion
                show-checkbox
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="统计规则：" prop="treeData">
          <div class="clearfix" v-if="paramsList.length > 0">
            <div class="cable fl" v-if="paramsList.length > 1">
              <span @click="changeAndOr">{{ andOr }}</span>
            </div>
            <div
              :class="[{ mL: paramsList.length > 1 }, 'fl', 'moreSearchBox']"
            >
              <div
                v-for="(item, index) in paramsList"
                :key="index"
                class="moreSearchList clearfix"
              >
                <el-form-item label="" class="row-padding-bottom fl">
                  <el-select
                    v-model="item.name"
                    class="moreSearchListLeft sWidth"
                    @change="changeOrder(item)"
                    placeholder="请选择"
                    filterable
                  >
                    <el-option
                      v-for="(items, indexs) in orderList.filter((obj) => {
                        return obj.isCheck
                      })"
                      :key="indexs"
                      :label="items.name"
                      :value="items.name"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div
                  class="showBetwwen fl"
                  v-if="
                    item.code !== 'last_punch_time' &&
                    item.code !== 'last_create_salary_table_date' &&
                    item.code !== 'last_salary_arrive_date'
                  "
                  style="display: inline-block"
                >
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-if="item.valueType == 'between'"
                  >
                    <el-input
                      class="moreSearchListNum"
                      placeholder="输入数值"
                      v-model="item.minValue"
                      clearable
                      oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')}"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl rangeWidth mLTen"
                    v-if="item.valueType == 'between'"
                  >
                    <el-select v-model="item.minValueCompareType">
                      <el-option label="＜" value="0"></el-option>
                      <el-option label="≤" value="1"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-if="item.valueType == 'between'"
                  >
                    <span>范围</span>
                  </el-form-item>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl rangeWidth mLTen"
                    v-if="item.valueType == 'between'"
                  >
                    <el-select v-model="item.maxValueCompareType">
                      <el-option label="＜" value="0"></el-option>
                      <el-option label="≤" value="1"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-if="item.valueType == 'between'"
                  >
                    <el-input
                      class="moreSearchListNum"
                      placeholder="输入数值"
                      v-model="item.maxValue"
                      clearable
                      oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')}"
                    ></el-input>
                    <!--限制只能输入正整数且保留两位小数-->
                  </el-form-item>
                </div>
                <el-form-item
                  label=""
                  class="row-padding-bottom fl mLTen"
                  v-if="item.valueType == 'select' && item.code == 'is_ps'"
                  style="margin-left: 25px"
                >
                  <el-select
                    v-model="item.minValue"
                    placeholder="请选择"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in isSetup"
                      :key="index"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label=""
                  class="row-padding-bottom fl mLTen"
                  v-if="item.valueType == 'select' && item.code == 'is_sa'"
                  style="margin-left: 25px"
                >
                  <el-select
                    v-model="item.minValue"
                    placeholder="请选择"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in isOpenData"
                      :key="index"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label=""
                  class="row-padding-bottom fl mLTen"
                  v-if="
                    item.valueType == 'select' &&
                    item.code == 'is_equip_att_machine'
                  "
                  style="margin-left: 25px"
                >
                  <el-select
                    v-model="item.minValue"
                    placeholder="请选择"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in isEquip"
                      :key="index"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- 专户是否签约 -->
                <el-form-item
                  label=""
                  class="row-padding-bottom fl mLTen"
                  v-if="item.valueType == 'select' && item.code == 'is_signed'"
                  style="margin-left: 25px"
                >
                  <el-select
                    v-model="item.minValue"
                    placeholder="请选择"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in isSignedData"
                      :key="index"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <!-- 日期类型的 -->
                <div
                  class="fl"
                  v-show="item.code == 'last_punch_time'"
                  style="display: inline-block"
                >
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-if="item.maxValueCompareType == 1"
                  >
                    <el-input
                      class="moreSearchListNum"
                      placeholder="输入数值"
                      v-model="item.minValue"
                      clearable
                      oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')}"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-else
                  >
                    <el-input
                      class="moreSearchListNum"
                      placeholder="输入数值"
                      v-model="item.maxValue"
                      clearable
                      oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')}"
                    ></el-input>
                  </el-form-item>
                  <span class="fl mLTen">天</span>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    style="margin-left: 25px"
                  >
                    <el-select
                      v-model="item.maxValueCompareType"
                      placeholder="请选择"
                      clearable
                      filterable
                      @change="changeDate($event, item, index)"
                    >
                      <el-option key="1" label="之内" value="1"></el-option>
                      <el-option key="2" label="之前" value="0"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-tooltip
                    content="之内包含当天；之前查询时段为【开始】—【当前日期减去所填天数】，比如当前日期为2020年3月20日，填写过去15天之前，即查询【开始】-【2020年3月5日】；"
                    placement="top"
                    class="mLTen"
                  >
                    <i class="icon iconfont icontishi"></i>
                  </el-tooltip>
                </div>
                <!-- 月份类型的 -->
                <div
                  class="fl"
                  v-show="
                    item.code == 'last_create_salary_table_date' ||
                    item.code == 'last_salary_arrive_date'
                  "
                  style="display: inline-block"
                >
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-if="item.maxValueCompareType == 1"
                  >
                    <el-input
                      class="moreSearchListNum"
                      placeholder="输入数值"
                      v-model="item.minValue"
                      clearable
                      oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')}"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    v-else
                  >
                    <el-input
                      class="moreSearchListNum"
                      placeholder="输入数值"
                      v-model="item.maxValue"
                      clearable
                      oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')}"
                    ></el-input>
                  </el-form-item>
                  <span class="fl mLTen">个月</span>
                  <el-form-item
                    label=""
                    class="row-padding-bottom fl mLTen"
                    style="margin-left: 25px"
                  >
                    <el-select
                      v-model="item.maxValueCompareType"
                      placeholder="请选择"
                      clearable
                      filterable
                      @change="changeDate($event, item, index)"
                    >
                      <el-option key="1" label="之内" value="1"></el-option>
                      <el-option key="2" label="之前" value="0"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-tooltip
                    content="之内包含当前月；之前查询时段为【开始】—【当前年月减去所填月数】，比如当前月为2020年3月，填写过去2个月之前，即查询【开始】-【2020年1月】；"
                    placement="top"
                    class="mLTen"
                  >
                    <i class="icon iconfont icontishi"></i>
                  </el-tooltip>
                </div>
                <span class="buttonBox fl">
                  <el-link typr="primary" @click="del(index, item.id)"
                    >删除</el-link
                  >
                  <!-- <img src="../../../static/img/deposit/reduce.png" alt="" class = "funcBox"  @click="del(index,item.id)"> -->
                </span>
              </div>
            </div>
          </div>

          <div>
            <el-button
              type="text"
              class="actionBoxAdd"
              icon="el-icon-plus"
              @click="addParams"
              >新增</el-button
            >
          </div>
        </el-form-item>
        <el-form-item style="padding-top: 18px">
          <el-button type="primary" class="commonBut saveBtn" @click="submit"
            >保存</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: 'addDiyTable',
  data() {
    return {
      id: '',
      titleText: '报表设置',
      formData: {
        name: '',
        description: '',
      },
      treeData: [],
      rules: {
        name: [
          { required: true, message: '请输入报表名称' },
          { min: 1, max: 32, message: '支持输入1-32个字符', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入报表说明' },
          { min: 1, max: 256, message: '支持输入1-256个字符', trigger: 'blur' },
        ],
      },

      checkedKeys: [],
      selArr: [],
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'label',
      },

      paramsList: [],
      orderList: [],
      isSetup: [],
      isOpenData: [],
      isSignedData: [],
      isEquip: [],
      andOr: '且',
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.getSettingDetail(this.$route.query.id)
      this.id = this.$route.query.id
    } else {
      this.getTableFileds()
      this.getSelect()
    }
  },
  methods: {
    async getSettingDetail(reportId) {
      const results = await this.axios.post(
        '/api-s/statscondition/findbycode',
        { type: 'PROJECT_DETAIL' }
      )
      this.axios
        .get('api-s/cs/projectstats/customreport/detail', {
          params: { reportId },
        })
        .then((res) => {
          if (!res.data.hasError) {
            const { name, description, conditionVOS, dimensionVOS } =
              res.data.result
            this.formData = { name, description }

            const result = results.data.result
            for (var i = 0; i < result.length; i++) {
              var flag = false

              for (let j = 0; j < conditionVOS.length; j++) {
                if (result[i].name == conditionVOS[j].name) {
                  conditionVOS[j].type = result[i].type
                  conditionVOS[j].id = result[i].id
                  conditionVOS[j].maxValueCompareType += ''
                  conditionVOS[j].minValueCompareType += ''
                  conditionVOS[j].hasDefaultValue = result[i].hasDefaultValue
                  conditionVOS[j].valueType = result[i].valueType
                  //最后考勤日期
                  if (conditionVOS[j].operateType == 'DATE_BETWEEN') {
                    if (conditionVOS[j].maxValueCompareType == 1) {
                      conditionVOS[j].minValue = conditionVOS[j].value
                      conditionVOS[j].maxValue = ''
                    } else {
                      conditionVOS[j].maxValue = conditionVOS[j].value
                    }
                  }
                  //
                  if (
                    result[i].hasDefaultValue == 0 ||
                    result[i].hasDefaultValue == '0'
                  ) {
                    this.getIsOpenData(result[i].id, result[i].code)
                  }
                  flag = true
                }
              }
              if (flag) {
                result[i].isCheck = false
              }
            }
            for (let i = 0, len = dimensionVOS.length; i < len; i++) {
              for (
                let j = 0, childLen = dimensionVOS[i].children.length;
                j < childLen;
                j++
              ) {
                var childrenData = dimensionVOS[i].children[j]
                if (
                  childrenData.prop == 'projectName' ||
                  childrenData.prop == 'cityName' ||
                  childrenData.prop == 'areaName' ||
                  childrenData.prop == 'industryName' ||
                  childrenData.prop == 'countyName' ||
                  childrenData.prop == 'townName' ||
                  childrenData.prop == 'investmentDesc'
                ) {
                  childrenData.disabled = true
                }
              }
            }
            this.paramsList = conditionVOS
            this.orderList = result
            this.treeData = dimensionVOS
            this.getTableAllLists()
          }
        })
    },
    changeDate($event, item, index) {
      if ($event == 1) {
        item.minValue = item.maxValue
        item.maxValue = ''
      } else {
        item.maxValue = item.minValue
        item.minValue = ''
      }
      this.$set(this.paramsList, index, item)
    },
    goBack() {
      this.$router.push('/home/statement/diyTable')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/statement/diyTable',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getTableFileds() {
      this.axios({
        method: 'post',
        url: '/api-s/dimension/head?type=' + 'PROJECT_DETAIL' + '&complex=1',
      }).then((res) => {
        var result = res.data.result
        // this.colSetupTableTotle = JSON.parse(JSON.stringify(result));
        //项目名称、区域、行业禁止筛选
        for (let i = 0, len = result.length; i < len; i++) {
          for (
            let j = 0, childLen = result[i].children.length;
            j < childLen;
            j++
          ) {
            var childrenData = result[i].children[j]
            if (
              childrenData.prop == 'projectName' ||
              childrenData.prop == 'cityName' ||
              childrenData.prop == 'areaName' ||
              childrenData.prop == 'industryName' ||
              childrenData.prop == 'countyName' ||
              childrenData.prop == 'townName' ||
              childrenData.prop == 'investmentDesc'
            ) {
              childrenData.disabled = true
            }
          }
        }
        this.treeData = result
        this.getTableAllLists()
      })
    },
    getSelect() {
      this.axios({
        method: 'post',
        url: '/api-s/statscondition/findbycode',
        data: {
          type: 'PROJECT_DETAIL',
          // ids: JSON.stringify(this.bb)
        },
      })
        .then((res) => {
          this.orderList = res.data.result
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取数据失败',
            type: 'error',
          })
        })
    },
    getIsOpenData(id, code) {
      this.axios({
        method: 'post',
        url: 'api-s/conditiondefault/findbyid',
        data: { conditionId: id },
      }).then((res) => {
        if (code == 'is_ps') {
          this.isSetup = res.data.result
        } else if (code == 'is_sa') {
          this.isOpenData = res.data.result
        } else if (code == 'is_signed') {
          this.isSignedData = res.data.result
        } else {
          this.isEquip = res.data.result
        }
      })
    },
    // 获取选中的节点数组
    getTableAllLists() {
      this.selArr = []
      this.selectKeys(this.treeData)
      // 给选中的节点前添加对号
      this.checkedKeys = this.selArr
      this.checkStrictly = false
    },
    // 查找已经被选中的节点
    selectKeys(menuList) {
      for (let menu of menuList) {
        if (menu.isShow) {
          this.selArr.push(menu.id)
        }
        if (menu.children) {
          this.selectKeys(menu.children)
        }
      }
    },
    //所有默认导出设置为否
    setDefaultFalse(arr) {
      for (let item of arr) {
        item.isShow = false
        if (item.children && item.children.length > 0) {
          this.setDefaultFalse(item.children)
        }
      }
    },
    //设置选中节点为导出字段
    setDefauled(arr, list) {
      for (let item of arr) {
        list.forEach((m) => {
          m.children.forEach((n) => {
            if (item == n.id) {
              n.isShow = true
            }
          })
        })
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      // 节点被选中时，获取所有选中的节点id
      let arr = this.$refs.headerList
        .getCheckedKeys()
        .concat(this.$refs.headerList.getHalfCheckedKeys())
      this.setDefaultFalse(this.treeData)
      this.setDefauled(arr, this.treeData)
    },

    getStartTimeItem(index, e) {
      this.paramsList[e].minValue = index ? index : ''
    },
    getEndTimeItem(index, e) {
      this.paramsList[e].maxValue = index ? index : ''
    },
    searchList() {
      var that = this
      that.dialogVisible = true
      that.percentage = 0
      that.paramsList.forEach(function (element, index) {
        for (var key in element) {
          if (element.name == '') {
            that.paramsList.splice(index, 1)
          }
        }
      })
      this.isShowAdd = true
      var paramsList = that.packageParams(that.paramsList)
      that.filterField.params = paramsList
      that.startPro = setInterval(function () {
        that.percentage += 30
        if (that.percentage > 70) {
          clearInterval(that.startPro)
          that.$nextTick(function () {
            that.$refs.pagination.getTableListData()
          })
        }
      }, 50)
    },
    //新增条件筛选
    addParams() {
      this.paramsList.push({
        name: '',
        valueType: '',
        minValue: '',
        maxValue: '',
        id: '',
        hasDefaultValue: '',
        operateType: '',
        code: '',
        maxValueCompareType: '1',
        minValueCompareType: '1',
      })
    },
    changeOrder(item) {
      for (var i = 0; i < this.orderList.length; i++) {
        var flag = true
        for (let j = 0; j < this.paramsList.length; j++) {
          if (this.orderList[i].name == this.paramsList[j].name) {
            this.paramsList[j].valueType = this.orderList[i].valueType
            this.paramsList[j].id = this.orderList[i].id
            this.paramsList[j].hasDefaultValue =
              this.orderList[i].hasDefaultValue
            this.paramsList[j].code = this.orderList[i].code
            this.paramsList[j].operateType = this.orderList[i].type
            this.orderList[i].isCheck = false
            flag = false
          }
        }
        if (flag) {
          this.orderList[i].isCheck = true
        }
      }
      if (item.hasDefaultValue == 0 || item.hasDefaultValue == '0') {
        this.getIsOpenData(item.id, item.code)
      }
    },
    del(index, value) {
      var that = this
      that.paramsList.splice(index, 1)
      var orderList = that.orderList
      for (var i = 0; i < orderList.length; i++) {
        if (orderList[i].id == value) {
          orderList[i].isCheck = true
        }
      }
    },
    // 条件筛选且或
    changeAndOr() {
      if (this.andOr == '且') {
        this.andOr = '或'
      } else {
        this.andOr = '且'
      }
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.getTableAllLists()
          let params = this.formData
          params.dimensionIds = this.checkedKeys.join(',')
          params.params = JSON.stringify(this.paramsList)
          params.logicOperator = this.andOr == '且' ? 'and' : 'or'
          if (this.id) {
            params.id = this.id
            this.axios
              .post('api-s/cs/projectstats/customreport/modify', params)
              .then((res) => {
                if (!res.data.hasError) {
                  this.$message({
                    message: '自定义报表设置修改成功',
                    type: 'success',
                    duration: 2000,
                  })
                  this.goBack()
                }
              })
          } else {
            this.axios
              .post('api-s/cs/projectstats/customreport/add', params)
              .then((res) => {
                if (!res.data.hasError) {
                  this.$message({
                    message: '自定义报表设置成功',
                    type: 'success',
                    duration: 2000,
                  })
                  this.goBack()
                }
              })
          }
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
.mainCon {
  padding: 40px 80px 40px 20px;
}
.moreSearchList {
  margin-bottom: 16px;
}
.cable {
  position: absolute;
  left: 0px;
  top: 0;
  bottom: 62px;
  margin-top: 8px;
  margin-right: 5px;
  margin-bottom: 8px;
  &:before {
    content: ' ';
    position: absolute;
    top: 0;
    left: 50%;
    width: 2px;
    height: 100%;
    overflow: hidden;
    background: #d6efe8;
  }
  > span {
    width: 18px;
    height: 18px;
    line-height: 18px;
    font-size: 12px;
    position: relative;
    display: block;
    top: 50%;
    left: 0;
    right: 0;
    transform: translateY(-50%);
    border-radius: 3px;
    background: #d6efe8;
    color: #009588;
    font-weight: 700;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
}
.theme_default .cable {
  &:before {
    background: #3189ea;
    opacity: 0.2;
  }
  > span {
    color: #3189ea;
    background: rgba(49, 137, 234, 0.2);
  }
}
/deep/.showBetwwen .el-input__inner {
  width: 105px !important;
}
.actionBox {
  position: relative;
  padding-left: 112px;
  &Add {
    line-height: 34px;
    // border-radius: 18px;
    width: auto;
    border-color: #009588;
    color: #009588;
    padding: 0 15px;
  }
  &Search {
    position: absolute;
    top: 0;
    right: 17px;
  }
  .searchBut {
    float: right;
  }
}
.mL {
  margin-left: 25px;
}
.mLTen {
  margin-left: 10px !important;
}
/deep/.rangeWidth .el-input__inner {
  width: 70px;
}
.elTree {
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  padding: 10px;
}
.buttonBox {
  float: left;
  margin-left: 15px;
}
</style>
